import React, { useState, useEffect } from 'react';
import {Table, Button, Modal, Form, Input, DatePicker, message, Card, Descriptions, Space, Popconfirm, Select,} from 'antd';
import {SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined,} from '@ant-design/icons';
import dayjs from 'dayjs';

const { TextArea } = Input;

// 模拟用户和班组映射
const userMap = {
    1: '张三',
    2: '李四',
    3: '王五',
};

const laborTeamMap = {
    1: '一号班组',
    2: '二号班组',
    3: '三号班组',
};

// 状态映射
const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已完成',
    3: '已延期',
};

// 模拟初始数据
const mockProjects = [
    {
        id: 1,
        name: '城市花园项目',
        create_time: '2023-01-15',
        end_time: '2025-01-15',
        projectManager: 1,
        builder: 2,
        laborTeam: 1,
        remark: '一期工程',
        status: 0,
    }
];

const ProjectManagement = () => {
    const [projects, setProjects] = useState([]);
    const [filteredProjects, setFilteredProjects] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [currentProject, setCurrentProject] = useState(null);
    const [searchText, setSearchText] = useState('');
    const [form] = Form.useForm();
    const [addForm] = Form.useForm();
    const [filterStatus, setFilterStatus] = useState(null);

    useEffect(() => {
        setProjects(mockProjects);
        setFilteredProjects(mockProjects);
    }, []);

    // 搜索 & 筛选
    const handleSearch = (value, status) => {
        setSearchText(value);
        setFilterStatus(status);

        let filtered = projects;

        if (value) {
            filtered = filtered.filter(project =>
                project.name.toLowerCase().includes(value.toLowerCase())
            );
        }

        if (status != null) {
            filtered = filtered.filter(project => project.status === status);
        }

        setFilteredProjects(filtered);
    };

    // 新增
    const showAddModal = () => {
        addForm.resetFields();
        setIsAddModalVisible(true);
    };

    const handleAdd = () => {
        addForm.validateFields().then(values => {
            const newId = projects.length > 0 ? Math.max(...projects.map(p => Number(p.id))) + 1 : 1;

            const newProject = {
                id: newId.toString(),
                ...values,
                create_time: values.create_time.format('YYYY-MM-DD'),
                end_time: values.end_time.format('YYYY-MM-DD'),
            };

            const updatedProjects = [...projects, newProject];
            setProjects(updatedProjects);
            setFilteredProjects(updatedProjects);
            setIsAddModalVisible(false);
            message.success('项目添加成功');
        });
    };

    // 编辑
    const showEditModal = (project) => {
        setCurrentProject(project);
        form.setFieldsValue({
            ...project,
            create_time: dayjs(project.create_time),
            end_time: dayjs(project.end_time),
        });
        setIsModalVisible(true);
    };

    const handleSave = () => {
        form.validateFields().then(values => {
            const updatedProjects = projects.map(p =>
                p.id === currentProject.id
                    ? {
                        ...p,
                        ...values,
                        create_time: values.create_time.format('YYYY-MM-DD'),
                        end_time: values.end_time.format('YYYY-MM-DD'),
                    }
                    : p
            );
            setProjects(updatedProjects);
            setFilteredProjects(updatedProjects);
            setIsModalVisible(false);
            message.success('项目信息更新成功');
        });
    };

    // 删除
    const handleDelete = (id) => {
        const updatedProjects = projects.filter(p => p.id !== id);
        setProjects(updatedProjects);
        setFilteredProjects(updatedProjects);
        message.success('项目删除成功');
    };

    // 详情
    const showDetailModal = (project) => {
        setCurrentProject(project);
        setIsDetailModalVisible(true);
    };

    const columns = [
        { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
        {
            title: '项目名称',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => showDetailModal(record)}>{text}</a>
            ),
        },
        {
            title: '开始时间',
            dataIndex: 'create_time',
            key: 'create_time',
        },
        {
            title: '结束时间',
            dataIndex: 'end_time',
            key: 'end_time',
        },
        {
            title: '项目经理',
            dataIndex: 'projectManager',
            key: 'projectManager',
            render: (val) => userMap[val],
        },
        {
            title: '施工方',
            dataIndex: 'builder',
            key: 'builder',
            render: (val) => userMap[val],
        },
        {
            title: '劳务班组',
            dataIndex: 'laborTeam',
            key: 'laborTeam',
            render: (val) => laborTeamMap[val],
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (val) => statusMap[val],
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space>
                    <Button type="link" icon={<EditOutlined />} onClick={() => showEditModal(record)} />
                    <Popconfirm
                        title="确定要删除此项目吗?"
                        onConfirm={() => handleDelete(record.id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button type="link" danger icon={<DeleteOutlined />} />
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <div style={{ padding: 24 }}>
            <Card
                title="项目管理"
                extra={
                    <Space>
                        <Input.Search
                            placeholder="搜索项目名称"
                            allowClear
                            enterButton={<SearchOutlined />}
                            value={searchText}
                            onChange={(e) => handleSearch(e.target.value, filterStatus)}
                            onSearch={(val) => handleSearch(val, filterStatus)}
                            style={{ width: 300 }}
                        />
                        <Select
                            style={{ width: 200 }}
                            placeholder="筛选状态"
                            allowClear
                            value={filterStatus}
                            onChange={(val) => handleSearch(searchText, val)}
                        >
                            {Object.keys(statusMap).map(k => (
                                <Select.Option key={k} value={Number(k)}>
                                    {statusMap[k]}
                                </Select.Option>
                            ))}
                        </Select>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={showAddModal}
                        >
                            新增项目
                        </Button>
                    </Space>
                }
            >
                <Table
                    columns={columns}
                    dataSource={filteredProjects}
                    rowKey="id"
                    bordered
                    pagination={{ pageSize: 10 }}
                />
            </Card>

            {/* 编辑模态框 */}
            <Modal
                title="编辑项目信息"
                open={isModalVisible}
                onOk={handleSave}
                onCancel={() => setIsModalVisible(false)}
                width={800}
            >
                <Form form={form} layout="vertical">
                    <Form.Item name="name" label="项目名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="create_time" label="开始时间" rules={[{ required: true }]}>
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="end_time" label="结束时间" rules={[{ required: true }]}>
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="projectManager" label="项目经理" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(userMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="builder" label="施工方" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(userMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="laborTeam" label="劳务班组" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(laborTeamMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="status" label="状态" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(statusMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="remark" label="备注">
                        <TextArea rows={3} />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 新增模态框 */}
            <Modal
                title="新增项目"
                open={isAddModalVisible}
                onOk={handleAdd}
                onCancel={() => setIsAddModalVisible(false)}
                width={800}
            >
                <Form form={addForm} layout="vertical">
                    <Form.Item name="name" label="项目名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="create_time" label="开始时间" rules={[{ required: true }]}>
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="end_time" label="结束时间" rules={[{ required: true }]}>
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="projectManager" label="项目经理" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(userMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="builder" label="施工方" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(userMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="laborTeam" label="劳务班组" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(laborTeamMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="status" label="状态" rules={[{ required: true }]}>
                        <Select>
                            {Object.entries(statusMap).map(([id, name]) => (
                                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="remark" label="备注">
                        <TextArea rows={3} />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 详情模态框 */}
            <Modal
                title="项目详情"
                open={isDetailModalVisible}
                onCancel={() => setIsDetailModalVisible(false)}
                footer={[
                    <Button key="edit" type="primary" onClick={() => {
                        setIsDetailModalVisible(false);
                        showEditModal(currentProject);
                    }}>
                        编辑
                    </Button>,
                    <Button key="close" onClick={() => setIsDetailModalVisible(false)}>关闭</Button>
                ]}
                width={800}
            >
                {currentProject && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="ID">{currentProject.id}</Descriptions.Item>
                        <Descriptions.Item label="项目名称">{currentProject.name}</Descriptions.Item>
                        <Descriptions.Item label="开始时间">{currentProject.create_time}</Descriptions.Item>
                        <Descriptions.Item label="结束时间">{currentProject.end_time}</Descriptions.Item>
                        <Descriptions.Item label="项目经理">{userMap[currentProject.projectManager]}</Descriptions.Item>
                        <Descriptions.Item label="施工方">{userMap[currentProject.builder]}</Descriptions.Item>
                        <Descriptions.Item label="劳务班组">{laborTeamMap[currentProject.laborTeam]}</Descriptions.Item>
                        <Descriptions.Item label="状态">{statusMap[currentProject.status]}</Descriptions.Item>
                        <Descriptions.Item label="备注" span={2}>{currentProject.remark}</Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>
        </div>
    );
};

export default ProjectManagement;
